#include "Callback.h"
#include "HsManange.h"
#include <string>
#include <vector>

using namespace HST3;

constexpr int MAX_CONN_COUNT = 2;

std::vector<IT3Connection *> InitConnection(IT3Config *lpConfig, MyCallback *lpcallback);

IT3Config *Configer()
{
    IT3Config *lpConfig = NewConfig(); // 配置对象指针，可以定义多个（多个连接使用不同配置文件时）
    lpConfig->AddRef();

    if (lpConfig->Load("./t3sdk.ini") != 0)
    {
        fmt::print("load config failed..\n");
    }

    return lpConfig;
}

// sync test
std::string SendAndRecv(IT3Connection *conn)
{
    auto data = hsRequest.SerialStr();

    int result = conn->Send(data.first, data.second, 0);
    if (result < 0)
    {
        fmt::print("Error: Send failed\n");
    }

    void *recvData = nullptr;
    int recvLen = 0;
    int recvRet = conn->Receive(result, &recvData, &recvLen, 1000, IT3Connection::JustRemoveHandle);
    if (recvRet != 0)
    {
        fmt::print("Error: Receive failed\n");
        return {};
    }

    return ParseBody(recvData, recvLen).RspBody;
}

int main(int argc, char *argv[])
{
    T3sdkInit();

    IT3Config *configer = Configer();
    // 通过T3SDK的引出函数，来获取一个新的IT3Message对象指针。传入消息类型、功能号和是否压缩

    MyCallback callback;

    std::vector<IT3Connection *> lpConnections = InitConnection(configer, &callback);
    if (lpConnections.empty())
    {
        fmt::print("connect failed..\n");
        return 0;
    }

    auto conn = lpConnections[0];

    SubscribePush(lpConnections[0]);
    LoginRequest();

    auto data = hsRequest.SerialStr();
    int ret = conn->Send(data.first, data.second, 1);
    fmt::print("[Send] conn = {}, hSend = {}\n", fmt::ptr(conn), ret);

    // lpConnections[0]->Release();
    // m_Subscriber->Release();
    // m_Subscriber = nullptr;
    ::sleep(1);
    // SubscribePush(lpConnections[1]);

    getchar();

    T3sdkUnInit();
    return 0;
}

/*
void SyncTest()
{
    LoginRequest();
    std::string answer = SendAndRecv(conn);
    if (!answer.empty())
    {
        ParseLogin(answer);
        QueryPosition();
        std::string ans = SendAndRecv(conn);
        QueryFund();
        ans = SendAndRecv(conn);
    }
}
*/

std::vector<IT3Connection *> InitConnection(IT3Config *lpConfig, MyCallback *lpcallback)
{
    std::vector<IT3Connection *> conns;
    /* 建立多个连接 */
    for (int i = 0; i < MAX_CONN_COUNT; i++)
    {
        IT3Connection *conn = NewConnection(lpConfig); // 申请连接对象
        conn->AddRef();

        if (conn->Create(lpcallback)) // 创建连接对象
        {
            printf("Create connection error!\n");
            return conns;
        }

        int ret = conn->Connect(5000);
        if (ret != 0) // timeout为0，建立异步连接 连接上时 OnRegister通知
        {
            fmt::print("connect error! {}\n", conn->GetErrorMsg(ret));
            return conns;
        }

        conns.push_back(conn);
    }

    ::sleep(1); // 等待连接注册成功

    return conns;
}